package com.centaline.androidsalesblog.activities.sale;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.AppCompatTextView;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;

import com.android.volley.VolleyError;
import com.bumptech.glide.BitmapTypeRequest;
import com.centaline.androidsalesblog.R;
import com.centaline.androidsalesblog.activities.news.ChatActivity;
import com.centaline.androidsalesblog.adapter.TabFragmentAdapter;
import com.centaline.androidsalesblog.api.sale.StaffApi;
import com.centaline.androidsalesblog.base.BaseActivity;
import com.centaline.androidsalesblog.constants.ExtraConstant;
import com.centaline.androidsalesblog.fragments.list.RentOfStaffFragment;
import com.centaline.androidsalesblog.fragments.list.SaleOfStaffFragment;
import com.centaline.androidsalesblog.model.businissobject.ShareBo;
import com.centaline.androidsalesblog.model.businissobject.StaffEstatePostGroupBo;
import com.centaline.androidsalesblog.model.databaseobject.BizUnitDo;
import com.centaline.androidsalesblog.model.databaseobject.StaffDo;
import com.centaline.androidsalesblog.model.responseobject.StaffRo;
import com.centaline.androidsalesblog.rx.database.RxDataBase;
import com.centaline.androidsalesblog.utils.ContactUtil;
import com.centaline.androidsalesblog.utils.RongUserIdUtil;
import com.centaline.androidsalesblog.widgets.ShareDialog;
import com.centanet.framework.glide.GlideLoad;
import com.centanet.framework.glide.RoundImageViewTarget;
import com.centanet.framework.interfaces.IResponseListener;
import com.trello.rxlifecycle.ActivityEvent;

import java.util.ArrayList;
import java.util.Locale;

import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * 经纪人详情
 */
public class StaffDetailActivity extends BaseActivity implements View.OnClickListener {

    private ImageView img_staff, img_chat;
    private AppCompatTextView atv_store, atv_desc;
    private TabLayout tab;
    private ViewPager viewPager;

    private ArrayList<Fragment> fragmentArrayList = new ArrayList<>();
    private ArrayList<String> titleArrayList = new ArrayList<>();
    private StaffDo staffDo;

    private StaffApi staffApi;

    private String shareUrl;
    private ShareDialog shareDialog;

    private BitmapTypeRequest<String> mBitmapTypeRequest;

    @Override
    protected int setLayoutId() {
        return R.layout.activity_staff_detail;
    }

    @Override
    protected void findViews() {
        setUniversalToolbar();
        img_staff = (ImageView) findViewById(R.id.img_staff);
        img_chat = (ImageView) findViewById(R.id.img_chat);
        atv_store = (AppCompatTextView) findViewById(R.id.atv_store);
        atv_desc = (AppCompatTextView) findViewById(R.id.atv_desc);
        tab = (TabLayout) findViewById(R.id.tab);
        viewPager = (ViewPager) findViewById(R.id.viewPager);
    }

    @Override
    protected void initViews() {
        mBitmapTypeRequest = GlideLoad.initRound(this);
        final String staffNo = getIntent().getStringExtra(ExtraConstant.StaffNo);

        Bundle bundle = new Bundle();
        bundle.putString(ExtraConstant.StaffNo, staffNo);

        SaleOfStaffFragment saleOfStaffFragment = new SaleOfStaffFragment();
        saleOfStaffFragment.setArguments(bundle);
        fragmentArrayList.add(saleOfStaffFragment);
        RentOfStaffFragment rentOfStaffFragment = new RentOfStaffFragment();
        rentOfStaffFragment.setArguments(bundle);
        fragmentArrayList.add(rentOfStaffFragment);
        titleArrayList.add("二手房");
        titleArrayList.add("租房");
        viewPager.setAdapter(new TabFragmentAdapter(getSupportFragmentManager(),
                fragmentArrayList, titleArrayList));
        tab.setupWithViewPager(viewPager);

        staffApi = new StaffApi(StaffDetailActivity.class, StaffRo.class, new IResponseListener<StaffRo>() {
            @Override
            public void onResponse(StaffRo staffRo) {
                staffDo = staffRo.getStaffDo();
                if (staffDo != null) {
                    setToolbarTitle(String.format("%s的店铺", staffDo.getCnName()));
                    invalidateOptionsMenu();
                    atv_store.setText(staffDo.getDepartmentName());
                    if (GlideLoad.needLoad(true)) {
                        mBitmapTypeRequest
                                .load(staffDo.getImgUrl())
                                .placeholder(R.drawable.ic_staff_default)
                                .error(R.drawable.ic_staff_default)
                                .centerCrop()
                                .into(new RoundImageViewTarget(img_staff));
                    } else {
                        mBitmapTypeRequest
                                .load("")
                                .placeholder(R.drawable.ic_staff_default)
                                .error(R.drawable.ic_staff_default)
                                .centerCrop()
                                .into(new RoundImageViewTarget(img_staff));
                    }
                    final ArrayList<StaffEstatePostGroupBo> staffEstatePostGroupBos = staffDo.getStaffEstatePostGroupBos();
                    if (staffEstatePostGroupBos != null &&
                            staffEstatePostGroupBos.size() > 0) {
                        StringBuilder stringBuilder = new StringBuilder();
                        for (StaffEstatePostGroupBo staffEstatePostGroupBo : staffEstatePostGroupBos) {
                            stringBuilder.append(staffEstatePostGroupBo.getName())
                                    .append("、");
                        }
                        stringBuilder.deleteCharAt(stringBuilder.length() - 1);
                        atv_desc.setText(String.format(Locale.CHINA, "服务小区:%s", stringBuilder.toString()));
                    }
                }
            }

            @Override
            public void onErrorResponse(VolleyError error) {
                netWorkUnable();
            }
        });
        staffApi.setStaffNo(staffNo);
        request();
        bizUnit();
    }

    private void request() {
        staffApi.startRequest();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_chat:
                startActivity(new Intent(this, ChatActivity.class)
                        .putExtra(ExtraConstant.TargetId, RongUserIdUtil.getSatffId(staffDo.getStaffNo())));
                baiduEvent("Z1_2_Click");
                break;
            case R.id.img_msg:
                ContactUtil.sendMsg(this, staffDo.getMobile());
                baiduEvent("Z1_3_Click");
                break;
            case R.id.img_call:
                new AlertDialog.Builder(this)
                        .setMessage(String.format(Locale.CHINA, "拨打:%s,%s",
                                staffDo.getBigCode(), staffDo.getExtCode()))
                        .setPositiveButton("拨打", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                ContactUtil.dial(StaffDetailActivity.this, staffDo.getBigCode(), staffDo.getExtCode());
                                baiduEvent("Z1_1_Click");
                            }
                        }).setNegativeButton("取消", null)
                        .create()
                        .show();
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_share, menu);
        MenuItem shareItem = menu.findItem(R.id.action_share);
        shareItem.setVisible(staffDo != null && !TextUtils.isEmpty(shareUrl));
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_share) {
            if (shareDialog == null) {
                ShareBo shareBo = new ShareBo(4);
                shareBo.setHouseName(String.format("%s的店铺", staffDo.getCnName()));
                shareBo.setHouseDecription(String.format(Locale.CHINA, "欢迎访问%s的店铺", staffDo.getCnName()));
                shareBo.setHouseUrl(shareUrl.replace("{0}", staffDo.getStaffNo()));
                shareBo.setImageUrl(staffDo.getImgUrl());
                shareDialog = new ShareDialog(this, shareBo);
            }
            shareDialog.show();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 获取配置
     */
    private void bizUnit() {
        RxDataBase.getBizUnit()
                .compose(this.<BizUnitDo>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<BizUnitDo>() {
                    @Override
                    public void call(BizUnitDo bizUnitDo) {
                        shareUrl = bizUnitDo.getShareJingjiren();
                        img_chat.setVisibility(bizUnitDo.isShowTalk() ? View.VISIBLE : View.GONE);
                        invalidateOptionsMenu();
                    }
                });
    }
}
